/*
 * @Author: 胡海
 * @Date: 2020-02-21 18:23:26
 * @LastEditors: 胡海
 * @LastEditTime: 2020-03-07 21:17:44
 * @Description: 
 */
const {
    sequelize
} = require('../../core/db.js')


const {
    Sequelize,
    Model,
    Op
} = require('sequelize')

const {
    Wimg
} = require('./w-imgM')

// define
class Wgoods extends Model {
    static async addgoods (ctx, v) { // 新增
        let request = {
            goodName: v.get('body.goodName'),
            price: v.get('body.price'),
            oldPrice: v.get('body.oldPrice'),
            inventory: v.get('body.inventory'),
            sales: v.get('body.sales'),
            introduction: v.get('body.introduction'),
        }
        const info = await Wgoods.findOne({
            where: {
                goodName: request.goodName
            }
        })
        console.log(info)
        if (info) {
            throw new global.errs.LikeError('产品已存在')
        }
        Wgoods.create(request)
    }
    static async editGoods (ctx, v) { // 修改
        let request = {
            goodName: v.get('body.goodName'),
            price: v.get('body.price'),
            oldPrice: v.get('body.oldPrice'),
            inventory: v.get('body.inventory'),
            sales: v.get('body.sales'),
            introduction: v.get('body.introduction'),
        }
        const info = await Wgoods.update(request, {
            where: {
                id: v.get('body.id')
            }
        })
    }
    static async delGoods (ctx, v) {// 删除
        const info = await Wgoods.destroy({
            where: {
                id: v.get('body.id')
            }
        })
    }
    static async list (ctx, v) { // 列表
        let request = {
            count: v.get('body.count'),
            start: v.get('body.start'),
        }
        let data = await Wgoods.findAndCountAll({
            // where: {
            //     goodsName: {
            //         [Op.like]: `%${obj.p}%`
            //     },
            //     // type: {
            //     //     [Op.like]: `%${obj.type}%`
            //     // },
            // },
            order: [
                ['id']
            ],
            limit: request.count,
            offset: (request.start - 1) * request.count,
        })
        let newList = []
        for(let item of data.rows){
            let obj = {
                ...item.dataValues,
                img: await Wimg.list(item.dataValues)
            }
            newList.push(obj)
        }
        let newData = {
            list:newList,
            total:data.count
        }
        return newData
    }
}

Wgoods.init({
    goodName: Sequelize.STRING,
    price: Sequelize.STRING,
    oldPrice: Sequelize.STRING,
    inventory: Sequelize.STRING,
    sales: Sequelize.STRING,
    introduction: Sequelize.STRING,
}, {
    sequelize,
    tableName: 'Wgoods',
    alter: true
})

module.exports = {
    Wgoods
}

// 数据迁移 SQL 更新 风险